<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { Button, message, Progress, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';

import { getMyQueueInfo, getQueueList, getQueueStatus } from '#/api/booking';

interface ServiceWindow {
  id: string;
  name: string;
  status: string;
  currentCustomer?: {
    customerName: string;
    startTime: string;
    ticketNumber: string;
  };
}

interface QueueInfo {
  ticketNumber: string;
  position: number;
  estimatedWaitTime: string;
  serviceWindow: string;
  totalInQueue: number;
}

interface QueueItem {
  ticketNumber: string;
  customerName: string;
  status: string;
}

interface Notification {
  id: string;
  type: 'info' | 'success' | 'warning';
  message: string;
  time: string;
}

const refreshing = ref(false);
const lastUpdateTime = ref('');
const serviceWindows = ref<ServiceWindow[]>([]);
const myQueueInfo = ref<null | QueueInfo>(null);
const queueList = ref<QueueItem[]>([]);
const notifications = ref<Notification[]>([]);

let refreshTimer: NodeJS.Timeout | null = null;
refreshTimer;

const refreshStatus = async () => {
  try {
    refreshing.value = true;

    // 并行加载所有数据
    const [statusData, queueInfo, queueListData] = await Promise.all([
      getQueueStatus(),
      getMyQueueInfo(),
      getQueueList(),
    ]);

    serviceWindows.value = statusData.windows;
    myQueueInfo.value = queueInfo;
    queueList.value = queueListData;

    lastUpdateTime.value = dayjs().format('HH:mm:ss');
  } catch (error) {
    console.error('刷新状态失败:', error);
    message.error('刷新状态失败');
  } finally {
    refreshing.value = false;
  }
};

const getWindowStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    BUSY: 'green',
    IDLE: 'blue',
    OFFLINE: 'red',
  };
  return colorMap[status] || 'default';
};

const getWindowStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    BUSY: '服务中',
    IDLE: '空闲',
    OFFLINE: '离线',
  };
  return textMap[status] || '未知';
};

const getQueueStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    WAITING: 'orange',
    CALLED: 'green',
    COMPLETED: 'default',
  };
  return colorMap[status] || 'default';
};

const getQueueStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    WAITING: '等待中',
    CALLED: '已叫号',
    COMPLETED: '已完成',
  };
  return textMap[status] || '未知';
};

const getNotificationIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    info: 'mdi:information',
    warning: 'mdi:alert',
    success: 'mdi:check-circle',
  };
  return iconMap[type] || 'mdi:information';
};

const getProgressPercent = (position: number, total: number) => {
  if (total === 0) return 0;
  return Math.round(((total - position + 1) / total) * 100);
};

const formatTime = (time: string) => {
  return dayjs(time).format('HH:mm:ss');
};

const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    refreshStatus();
  }, 10_000); // 每10秒刷新一次
};

const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

onMounted(() => {
  refreshStatus();
  startAutoRefresh();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<template>
  <div class="queue-status">
    <div class="status-header">
      <h2 class="title">排队状态</h2>
      <div class="refresh-info">
        <span class="last-update">最后更新: {{ lastUpdateTime }}</span>
        <Button @click="refreshStatus" :loading="refreshing" size="small">
          <IconifyIcon icon="mdi:refresh" />
        </Button>
      </div>
    </div>

    <!-- 当前服务窗口状态 -->
    <div class="current-service-section">
      <h3 class="section-title">当前服务</h3>
      <div class="service-windows">
        <div
          v-for="window in serviceWindows"
          :key="window.id"
          class="service-window"
        >
          <div class="window-header">
            <h4 class="window-name">{{ window.name }}</h4>
            <Tag :color="getWindowStatusColor(window.status)">
              {{ getWindowStatusText(window.status) }}
            </Tag>
          </div>

          <div class="current-customer" v-if="window.currentCustomer">
            <div class="customer-info">
              <span class="ticket-number">{{
                window.currentCustomer.ticketNumber
              }}</span>
              <span class="customer-name">{{
                window.currentCustomer.customerName
              }}</span>
            </div>
            <div class="service-time">
              <span class="label">服务开始：</span>
              <span class="time">{{
                formatTime(window.currentCustomer.startTime)
              }}</span>
            </div>
          </div>

          <div v-else class="no-customer">
            <IconifyIcon icon="mdi:account-off" />
            <span>暂无客户</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的排队信息 -->
    <div v-if="myQueueInfo" class="my-queue-section">
      <h3 class="section-title">我的排队</h3>
      <div class="my-queue-card">
        <div class="queue-info">
          <div class="ticket-display">
            <div class="ticket-number-large">
              {{ myQueueInfo.ticketNumber }}
            </div>
            <div class="ticket-label">我的号码</div>
          </div>

          <div class="queue-details">
            <div class="detail-row">
              <span class="label">排队位置：</span>
              <span class="value position">{{ myQueueInfo.position }}</span>
            </div>
            <div class="detail-row">
              <span class="label">预计等待：</span>
              <span class="value wait-time">{{
                myQueueInfo.estimatedWaitTime
              }}</span>
            </div>
            <div class="detail-row">
              <span class="label">服务窗口：</span>
              <span class="value window">{{ myQueueInfo.serviceWindow }}</span>
            </div>
          </div>
        </div>

        <div class="queue-progress">
          <div class="progress-info">
            <span>前面还有 {{ myQueueInfo.position - 1 }} 人</span>
            <span>预计 {{ myQueueInfo.estimatedWaitTime }} 后到您</span>
          </div>
          <Progress
            :percent="
              getProgressPercent(myQueueInfo.position, myQueueInfo.totalInQueue)
            "
            :show-info="false"
            stroke-color="#3b82f6"
          />
        </div>
      </div>
    </div>

    <!-- 排队列表 -->
    <div class="queue-list-section">
      <h3 class="section-title">排队列表</h3>
      <div class="queue-list">
        <div
          v-for="(item, index) in queueList"
          :key="item.ticketNumber"
          class="queue-item"
          :class="{
            'my-ticket': item.ticketNumber === myQueueInfo?.ticketNumber,
          }"
        >
          <div class="queue-position">{{ index + 1 }}</div>
          <div class="queue-ticket">
            <span class="ticket-number">{{ item.ticketNumber }}</span>
            <span class="customer-name">{{ item.customerName }}</span>
          </div>
          <div class="queue-status">
            <Tag :color="getQueueStatusColor(item.status)">
              {{ getQueueStatusText(item.status) }}
            </Tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 实时通知 -->
    <div v-if="notifications.length > 0" class="notifications-section">
      <h3 class="section-title">通知消息</h3>
      <div class="notifications-list">
        <div
          v-for="notification in notifications"
          :key="notification.id"
          class="notification-item"
          :class="notification.type"
        >
          <IconifyIcon :icon="getNotificationIcon(notification.type)" />
          <span class="notification-text">{{ notification.message }}</span>
          <span class="notification-time">{{
            formatTime(notification.time)
          }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.queue-status {
  padding: 20px;
}

.status-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.refresh-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.last-update {
  font-size: 14px;
  color: #6b7280;
}

.section-title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.current-service-section,
.my-queue-section,
.queue-list-section,
.notifications-section {
  margin-bottom: 32px;
}

.service-windows {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.service-window {
  padding: 16px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
}

.window-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.window-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.current-customer {
  padding: 12px;
  background: #f0f9ff;
  border-radius: 8px;
}

.customer-info {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
}

.ticket-number {
  font-size: 18px;
  font-weight: 700;
  color: #3b82f6;
}

.customer-name {
  font-weight: 500;
  color: #1f2937;
}

.service-time {
  font-size: 14px;
  color: #6b7280;
}

.service-time .label {
  margin-right: 4px;
}

.no-customer {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  padding: 20px;
  font-size: 14px;
  color: #6b7280;
  text-align: center;
}

.my-queue-card {
  padding: 24px;
  color: white;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 16px;
}

.queue-info {
  display: flex;
  gap: 24px;
  align-items: center;
  margin-bottom: 20px;
}

.ticket-display {
  text-align: center;
}

.ticket-number-large {
  font-size: 48px;
  font-weight: 700;
  line-height: 1;
}

.ticket-label {
  margin-top: 4px;
  font-size: 14px;
  opacity: 0.8;
}

.queue-details {
  flex: 1;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row .label {
  opacity: 0.8;
}

.detail-row .value {
  font-weight: 600;
}

.detail-row .value.position {
  color: #fbbf24;
}

.detail-row .value.wait-time {
  color: #34d399;
}

.queue-progress {
  padding: 16px;
  background: rgb(255 255 255 / 20%);
  border-radius: 8px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  opacity: 0.9;
}

.queue-list {
  overflow: hidden;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
}

.queue-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f3f4f6;
}

.queue-item:last-child {
  border-bottom: none;
}

.queue-item.my-ticket {
  background: #f0f9ff;
  border-left: 4px solid #3b82f6;
}

.queue-position {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 16px;
  font-weight: 600;
  color: #6b7280;
  background: #f3f4f6;
  border-radius: 50%;
}

.queue-ticket {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 4px;
}

.queue-ticket .ticket-number {
  font-weight: 600;
  color: #1f2937;
}

.queue-ticket .customer-name {
  font-size: 14px;
  color: #6b7280;
}

.notifications-list {
  overflow: hidden;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
}

.notification-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f3f4f6;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-item.info {
  background: #f0f9ff;
}

.notification-item.warning {
  background: #fffbeb;
}

.notification-item.success {
  background: #f0fdf4;
}

.notification-text {
  flex: 1;
  color: #1f2937;
}

.notification-time {
  font-size: 12px;
  color: #6b7280;
}
</style>
